package com.student.Activitys.activity;

import android.content.res.ColorStateList;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.facebook.drawee.view.SimpleDraweeView;
import com.student.Activitys.R;
import com.student.Activitys.activity.base.BaseActivity;
import com.student.Activitys.adapter.ScheduleDayAdapter;
import com.student.Activitys.adapter.base.BaseRecyleViewAdapter;
import com.student.Activitys.bean.InfoReturnBean;
import com.student.Activitys.bean.ScheduleWeekBean;
import com.student.Activitys.bean.pack.ScheduleJsonPack;
import com.student.Activitys.bean.pack.ScheduleTestingJsonPack;
import com.student.Activitys.dialog.ScheduleDayDialog;
import com.odd.Activitys.http.manager.ScheduleManager;
import com.student.Activitys.utils.Constant;
import com.student.Activitys.utils.DataUtils;
import com.student.Activitys.utils.JumperUtils;
import com.student.Activitys.utils.ToastUtils;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 项目名称：智慧校园学生端
 * 类描述：日课表 页面
 * 创建人：张飞祥
 * 创建时间：2017/9/26 9:57
 * 修改人：张飞祥
 * 修改时间：2017/9/26 9:57
 * 修改备注：
 */
public class ScheduleDayActivity extends BaseActivity {

    @Bind(R.id.sv_schedule_bg)
    SimpleDraweeView svScheduleBg;
    @Bind(R.id.tv_schedule_title)
    TextView tvScheduleTitle;
    @Bind(R.id.tv_schedule_date)
    TextView tvScheduleDate;
    @Bind(R.id.fb_schedule)
    FloatingActionButton fbSchedule;
    @Bind(R.id.iv_return)
    ImageView ivReturn;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.rv_day_schedule)
    RecyclerView rvDaySchedule;
    @Bind(R.id.app_bar_layout)
    AppBarLayout appBarLayout;

    //日课表 adapter
    private ScheduleDayAdapter adapter;
    //初始化网络请求
    public ScheduleManager mApiManager;
    //当前学年学期
    public String xnxq = "";
    //当前上课周次
    public String skzc = " ";
    //签到提示 diaolog
    public MaterialDialog signDialog;
    //评价 判断所需要传递的 bean
    public static ScheduleWeekBean testingBean = null;

    @Override
    protected void initUI() {
        setContentView(R.layout.act_day_schedule);
        //网络请求接口 常驻方法
        mApiManager = mApiManager.getScheduleApiManager(ScheduleDayActivity.this, ScheduleDayActivity.this.getTaskId());
    }

    @Override
    protected void initData() {
        //标题
        tvTitle.setText("日课表");
        //返回键
        ivReturn.setVisibility(View.VISIBLE);
        //设置悬浮按钮 属性
        fbSchedule.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.color_fb_schedule_day_bg)));
        fbSchedule.setImageResource(R.drawable.act_day_schedule_fb_icon);
        //获取当前日期
        tvScheduleTitle.setText(DataUtils.getNowDate("yyyy/MM/dd"));
        //获取当前星期
        tvScheduleDate.setText(DataUtils.getNowWeek());
        //请求日课表数据
        initViewRefresh();
        //设置标题背景
        appBarLayout.setBackgroundResource(R.color.schedule_bg_color);
        //设置头部背景
        svScheduleBg.setBackgroundResource(R.drawable.act_schedule_day_bg);
    }


    /**
     * 日课表 网络请求 加载是否成功
     */
    @Subscriber(tag = Constant.BUS_DAY_SCHEDULE_ON_COMPLETED,mode = ThreadMode.MAIN)
    public void initDayOnCompleted(String str) {
        //销毁handler
        time_handler.removeCallbacks(time_runnable);
        timeDailog.dismiss();
        dialog.dismiss();
    }

    /**
     * 日课表 网络请求 返回具体 数据实体
     */
    @Subscriber(tag = Constant.BUS_DAY_SCHEDULE_LIST,mode = ThreadMode.MAIN)
    public void initDayList(final ScheduleJsonPack pack) {
        final List<ScheduleWeekBean> data = getListSchedule(pack.getData());
        xnxq = pack.getXNXQ();  //获取学年学期
        skzc = pack.getSKZC();  //获取上课周次

        //塞入数据源
        adapter = new ScheduleDayAdapter(ScheduleDayActivity.this,data);
        rvDaySchedule.setLayoutManager(new LinearLayoutManager(ScheduleDayActivity.this, LinearLayoutManager.VERTICAL, false));
        rvDaySchedule.setAdapter(adapter);
        //条目点击事件
        adapter.setOnItemClickListener(new BaseRecyleViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (data.get(position).getSFQJ() != null)
                    onItemClickHandle(data.get(position));          //item 事件处理
                else
                    ToastUtils.showShort(ScheduleDayActivity.this,"没课点个屁啊~");
            }
        });
    }


    /**
     * 日课表 评价检测 加载是否成功
     */
    @Subscriber(tag = Constant.BUS_EVALUATE_TESTING_ON_COMPLETED,mode = ThreadMode.MAIN)
    public void initTestingOnCompleted(String str) {

    }

    /**
     * 日课表 评价检测 返回具体 数据实体
     */
    @Subscriber(tag = Constant.BUS_EVALUATE_TESTING_DETAILS_LIST,mode = ThreadMode.MAIN)
    public void initTestingList(final ScheduleTestingJsonPack pack) {
        if (pack.getState().equals("1")){
            if (pack.getWD_Data()!=null){
                Bundle bundle = new Bundle();
                bundle.putSerializable(Constant.EVALUATE_JSON_PACK, (Serializable) pack.getWD_Data());
                bundle.putParcelable(Constant.SCHEDULE_WEEK_BEAN,testingBean);
                bundle.putString(Constant.XNXQ,xnxq);
                bundle.putString(Constant.SKZC,skzc);
                JumperUtils.JumpTo(ScheduleDayActivity.this, EvaluateClassRoomActivity.class,bundle);           //跳转 评价页面
            }
        }else if(pack.getState().equals("2")){
            Bundle bundle = new Bundle();
            bundle.putSerializable(Constant.EVALUATE_PJFS, (Serializable) pack.getPJFS());
            bundle.putString(Constant.PJLY,pack.getPJLY());
            bundle.putString(Constant.SZDD,pack.getSKDD());
            JumperUtils.JumpTo(ScheduleDayActivity.this, EvaluateResultActivity.class,bundle);                   //跳转 评价详情
        }else{
            ToastUtils.showShort(getApplicationContext(),pack.getMsg());
        }
    }
    /**
     * 日课表 签到 网络请求 加载是否成功
     */
    @Subscriber(tag = Constant.BUS_DAY_SCHEDULE_SIGN_ON_COMPLETED, mode = ThreadMode.MAIN)
    public void initSignOnCompleted(String str) {
        //销毁handler
        time_handler.removeCallbacks(time_runnable);
        timeDailog.dismiss();
        dialog.dismiss();
    }

    /**
     * 日课表 签到 校内动态 网络请求 返回具体 数据实体
     */
    @Subscriber(tag = Constant.BUS_DAY_SCHEDULE_SIGN, mode = ThreadMode.MAIN)
    public void initSign(InfoReturnBean bean) {
        if (bean.getState().equals("1")){
            signDialog = new MaterialDialog.Builder(ScheduleDayActivity.this)
                    .title("成功")
                    .content("您已经"+bean.getQD_state()+"了！")
                    .positiveText("确认")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {
                            //刷新当前页面
                            initReturnRefresh();
                            signDialog.dismiss();
                        }
                    }).show();
        }else{
            signDialog = new MaterialDialog.Builder(ScheduleDayActivity.this)
                    .title("失败")
                    .content(bean.getMsg())
                    .positiveText("知道了")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {
                            signDialog.dismiss();
                        }
                    }).show();
        }
        // 设置点击屏幕Dialog不消失
        signDialog.setCanceledOnTouchOutside(false);
        //取消Back键监听
        signDialog.setCancelable(false);
    }

    /**
     * 所有点击事件
     * @param view
     */
    @OnClick({R.id.iv_return,R.id.fb_schedule})
    void OnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_return:    //退出
                finish();
                break;
            case R.id.fb_schedule:  //切换周课表
                if(!xnxq.equals("") && !skzc.equals("")){
                    Bundle bundle = new Bundle();
                    bundle.putString(Constant.XNXQ,xnxq);
                    bundle.putString(Constant.SKZC,skzc);
                    JumperUtils.JumpTo(ScheduleDayActivity.this,ScheduleWeekActivity.class,bundle);
                }
                break;
        }
    }

    /**
     * 日课表 底部弹窗
     *
     * @param bean
     */
    private void onItemClickHandle(final ScheduleWeekBean bean){

        //日课表 事件弹窗
        ScheduleDayDialog dayDialog = new ScheduleDayDialog(ScheduleDayActivity.this) {
            @Override
            public void evaluate() {    //评价事件
                testingBean = bean;
                //网络请求 评价检测
                mApiManager.evaluateTesting(Constant.HTTP_EVALUATE_TESTING_ACTION, Constant.STPJ, xnxq, xh, bean.getJSH(), bean.getKCH()
                        , bean.getSKJC(), bean.getSKXQ(), skzc, bean.getSKDD());
            }

            @Override
            public void feedback() {    //课堂反馈事件

            }

            @Override
            public void leave() {       //请假事件
                Bundle bundle = new Bundle();
                //存入 当前 item 实体
                bundle.putParcelable(Constant.SCHEDULE_WEEK_BEAN,bean);
                bundle.putString(Constant.SKZC,skzc);
                if (bean.getSFQJ().equals("0"))
                    JumperUtils.JumpTo(ScheduleDayActivity.this, LeaveActivity.class,bundle);           //跳转请假页面
                else
                    JumperUtils.JumpTo(ScheduleDayActivity.this, LeaveDetailsActivity.class,bundle);    //跳转已请假详情页面
            }

            @Override
            public void sign() {        //签到事件
                initSignHttp(bean);
            }
        };
        dayDialog.show();
    }

    //初始化加载 数据
    private void initViewRefresh() {
        //显示 加载dialog
        initShowTimeDialog("正在加载今天的课表，请稍后...",ScheduleDayActivity.this);
        //网络请求 日课表数据
        mApiManager.scheduleDayList(Constant.HTTP_DAY_SCHEDULE_ACTION,xh, DataUtils.getNowDate("yyyy-MM-dd"));
    }
    /**
     * 签到 http请求
     */
    private void initSignHttp(ScheduleWeekBean bean) {
        //显示 加载dialog
        initShowTimeDialog("正在签到，请稍后...",ScheduleDayActivity.this);
        //获取签到信息请求
        mApiManager.scheduleSign(Constant.HTTP_HOME_SIGN_ACTION,xh,bean.getJSH(),
                bean.getKCH(),xnxq,skzc,bean.getSKXQ(),
                bean.getSKJC(),bean.getJXB());
    }
    @Override
    protected void getNotData() {

    }

    /**
     * 将一个 size 为 6的空数据源，通过改造加入新的 数据并返回 (日课表  数据处理)
     *
     * @param list
     * @return
     */
    public List<ScheduleWeekBean> getListSchedule(List<ScheduleWeekBean> list) {
        List<ScheduleWeekBean> nullList = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            nullList.add(new ScheduleWeekBean());
        }
        for (int i = 0; i < list.size(); i++) {
            switch (list.get(i).getSKJC()) {
                case Constant.ONE:
                    nullList.remove(0);
                    nullList.add(0, list.get(i));
                    break;
                case Constant.TWO:
                    nullList.remove(1);
                    nullList.add(1, list.get(i));
                    break;
                case Constant.THREE:
                    nullList.remove(2);
                    nullList.add(2, list.get(i));
                    break;
                case Constant.FOUR:
                    nullList.remove(3);
                    nullList.add(3, list.get(i));
                    break;
                case Constant.FIVE:
                    nullList.remove(4);
                    nullList.add(4, list.get(i));
                    break;
                case Constant.SIX:
                    nullList.remove(5);
                    nullList.add(5, list.get(i));
                    break;
            }
        }
        return nullList;
    }

    /**
     * 日课表 刷新 消息通知
     */
    @Subscriber(tag = Constant.SCHEDULE_DAY_REFRESH,mode = ThreadMode.MAIN)
    public void initRefresh(String str) {
        initReturnRefresh();
    }


    /**
     * 刷新当前页面
     */
    public void initReturnRefresh(){
        timeSecond = 10;
        initViewRefresh();
    }

}
